package com.scriptlib;

import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.ImageReader;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;

//参考 https://cloud.tencent.com/developer/article/1719830
public class RecordHelper {

    private final String TAG = "RecordHelper";

    private VirtualDisplay _VirtualDisplay;
    private MediaRecorder _MediaRecorder;
    AJFunc _AJFunc;

    private final int Width;
    private final int Height;
    private final int Dpi;
    private final String Path;

    private boolean Running = false;

    public RecordHelper(Object obj, int width, int height, int dpi, String path) {
        _AJFunc = new AJFunc(obj);
        Width = width;
        Height = height;
        Dpi = dpi;
        Path = path;
    }

    public boolean Start() {

        MediaProjection _MediaProjection = _AJFunc.GetMediaProjection();
        _MediaRecorder = new MediaRecorder();
        _MediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        _MediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        _MediaRecorder.setOutputFile(Path);
        _MediaRecorder.setVideoSize(Width, Height);
        _MediaRecorder.setVideoFrameRate(24);
        _MediaRecorder.setVideoEncodingBitRate(Width * Height * 2);
        _MediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        try {
            _MediaRecorder.prepare();
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
            return false;
        }

        _VirtualDisplay = _MediaProjection.createVirtualDisplay(TAG + "-display", Width, Height, Dpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC, _MediaRecorder.getSurface(), null, null);
        Log.i(TAG, "created virtual display: " + _VirtualDisplay);

        _MediaRecorder.start();
        Log.i(TAG, "start");
        Running = true;
        return true;
    }

    public void Stop() {
        if (Running) {
            if (_VirtualDisplay != null) {
                _VirtualDisplay.release();
            }
            if (_MediaRecorder != null) {
                _MediaRecorder.setOnErrorListener(null);
                _MediaRecorder.stop();
                _MediaRecorder.reset();
                _MediaRecorder.release();
            }
            Running = false;
            Log.i(TAG, "Stop");
        }
    }

}
